import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/constans/hazard_investigation_code.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_user_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/base_danger_investigation_info_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/process_currency_execute_entity.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/hazard_investigation/hazard_management/hazard_management_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class HazardConfirmationController extends GetxController {
  /// 父类Controller
  final managementController = Get.find<HazardManagementController>();

  /// 隐患id
  String id = Get.arguments as String;

  /// 是否是展开状态
  bool isExpanded = false;

  /// 当前选中的标题索引，0：正常 1:存在隐患
  RxInt currentIndex = 0.obs;

  /// 接口上传的详情实体
  BaseDangerInvestigationInfoEntity infoEntity = BaseDangerInvestigationInfoEntity();

  /// 初始详情实体
  BaseDangerInvestigationInfoEntity initialEntity = BaseDangerInvestigationInfoEntity();

  /// 隐患等级选择
  GetDictAllEntity levelDict = GetDictAllEntity();

  /// 隐患类型选择
  GetDictAllEntity levelType = GetDictAllEntity();

  /// 隐患来源选择
  GetDictAllEntity levelSource = GetDictAllEntity();

  /// 隐患治理类型
  GetDictAllEntity levelManageSource = GetDictAllEntity();

  /// 流程节点执行实体
  ProcessCurrencyExecuteEntity executeEntity = ProcessCurrencyExecuteEntity();

  @override
  void onInit() {
    super.onInit();
    _getLedgerDetail();
  }

  /// 查询隐患治理详情
  Future<void> _getLedgerDetail() async {
    final res = await HttpUtil().generateGetRequest<BaseDangerInvestigationInfoEntity>(Interface.getLedgerDetail, queryParameters: {'id': id}).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        initialEntity = result.data!;
        infoEntity = BaseDangerInvestigationInfoEntity.fromJson(initialEntity.toJson());
        update();
      }
    });
  }

  /// title选择切换
  void selectTitle(int index) {
    infoEntity = BaseDangerInvestigationInfoEntity.fromJson(initialEntity.toJson());
    currentIndex.value = index;
  }

  /// 点击展开或者收起
  void onExpanded() {
    isExpanded = !isExpanded;
    update();
  }

  /// 选择隐患等级
  Future<void> selectDangerLevel() async {
    final List<GetDictAllEntity> dictList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'currency_danger_level');
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '隐患等级',
      dataList: dictList,
      checkedList: [levelDict],
      isMultiple: false,
      onCallBack: (value) {
        levelDict = value[0];
        infoEntity.dangerLevelDicId = value[0].getId();
        infoEntity.dangerLevel = value[0].getShowName();
        update();
      },
    );
  }

  /// 选择隐患类型
  Future<void> selectDangerType() async {
    final List<GetDictAllEntity> dictList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'currency_hazard_danger_type');
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '隐患类型',
      dataList: dictList,
      checkedList: [levelType],
      isMultiple: false,
      onCallBack: (value) {
        levelType = value[0];
        infoEntity.hazardDangerTypeDicId = value[0].getId();
        infoEntity.hazardDangerType = value[0].getShowName();
        update();
      },
    );
  }

  /// 选择隐患来源
  Future<void> selectDangerSource() async {
    final List<GetDictAllEntity> dictList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'hidden_danger_investigation_task_work_kind');
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '隐患来源',
      dataList: dictList,
      checkedList: [levelSource],
      isMultiple: false,
      onCallBack: (value) {
        levelSource = value[0];
        infoEntity.dangerSrcDicId = value[0].getId();
        infoEntity.dangerSrc = value[0].getShowName();
        update();
      },
    );
  }

  /// 选择隐患治理类型
  Future<void> selectDangerManageType() async {
    final List<GetDictAllEntity> dictList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'currency_danger_manage_type');
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '治理类型',
      dataList: dictList,
      checkedList: [levelManageSource],
      isMultiple: false,
      onCallBack: (value) {
        levelManageSource = value[0];
        infoEntity.dangerManageTypeDicId = value[0].getId();
        infoEntity.dangerManageType = value[0].getShowName();
        update();
      },
    );
  }

  /// 隐患治理期限时间选择
  void showDatePicker() {
    CustomSelectFunction.selectDateTime(onCallBack: (String value) {
      infoEntity.dangerManageDeadline = value;
      update();
    });
  }

  /// 选择整改负责人
  void selectResponsible() {
    Get.toNamed(AppRoutes.personnelDepartmentTreePage, arguments: {
      'title': '整改负责人',
      'type': '3',
      'isRadio': true,
    })?.then((value) {
      if (value != null) {
        final DepartmentUserEntity user = value[0] as DepartmentUserEntity;
        infoEntity.liablePerson = user.getShowName();
        infoEntity.liableUserId = user.getId();
        update();
      }
    });
  }

  /// 选择验收人
  void selectAcceptance() {
    Get.toNamed(AppRoutes.personnelDepartmentTreePage, arguments: {
      'title': '验收人',
      'type': '3',
      'isRadio': true,
    })?.then((value) {
      if (value != null) {
        final DepartmentUserEntity user = value[0] as DepartmentUserEntity;
        infoEntity.checkAcceptPerson = user.getShowName();
        infoEntity.checkAcceptUserId = user.getId();
        update();
      }
    });
  }

  /// 提交
  void complete() {
    if (currentIndex.value == 0) {
      completeNormal();
    } else {
      completeExistence();
    }
  }

  /// 正常
  void completeNormal() {
    if (infoEntity.checkAcceptComment!.isEmpty) {
      AppToast.showWarning('请输入驳回意见!');
      return;
    }
    // 修改状态为驳回
    infoEntity.dangerState = '10';
    processExecute();
  }

  /// 存在隐患
  void completeExistence() {
    if (infoEntity.dangerName!.isEmpty) {
      AppToast.showWarning('请输入隐患名称!');
      return;
    }
    if (infoEntity.dangerLevel!.isEmpty) {
      AppToast.showWarning('请选择隐患等级!');
      return;
    }
    if (infoEntity.hazardDangerType!.isEmpty) {
      AppToast.showWarning('请选择隐患类型!');
      return;
    }
    if (infoEntity.dangerSrc!.isEmpty) {
      AppToast.showWarning('请选择隐患来源!');
      return;
    }
    if (infoEntity.dangerManageType!.isEmpty) {
      AppToast.showWarning('请选择治理类型!');
      return;
    }
    if (infoEntity.dangerDesc!.isEmpty) {
      AppToast.showWarning('请输入隐患描述!');
      return;
    }
    if (infoEntity.dangerManageDeadline!.isEmpty) {
      AppToast.showWarning('请选择整改期限!');
      return;
    }
    if (infoEntity.liablePerson!.isEmpty) {
      AppToast.showWarning('请选择整改负责人!');
      return;
    }
    if (infoEntity.checkAcceptPerson!.isEmpty) {
      AppToast.showWarning('请选择验收人!');
      return;
    }
    // 修改状态为待整改
    infoEntity.dangerState = '0';
    processExecute();
  }

  ///流程节点执行
  Future<void> processExecute() async {
    // 后端要求把隐患等级名称置空
    infoEntity.dangerLevel = '';
    executeEntity.confirmDTO = infoEntity;
    executeEntity.processEncoding = HazardInvestigationCode.processEncoding;
    executeEntity.nodeId = managementController.implementNode.nodeId;
    executeEntity.rtemplateId = managementController.implementNode.rtemplateId;
    AppLogger.log(executeEntity.toJson().toString());
    // 调用流程节点执行接口
    final res = await HttpUtil().generatePostRequest(Interface.processLedgerExecute, data: executeEntity.toJson()).execute();
    res.onSuccess((result) {
      managementController.refreshPage();
      Get.back();
      AppToast.showSuccess('隐患确认成功');
    });
    res.onError((result) {
      AppToast.showError('隐患确认失败');
    });
  }
}
